﻿using System;
using System.Net;
using System.Text;

namespace Alderamin.Core
{
    /// <summary>
    /// Provides basic functions for handling http(s) connections. This is a abstract class
    /// </summary>
    public abstract class HttpHandlerBase
    {
        #region Protected Methods

        /// <summary>
        /// Create a POST http request withe the specified url, proxy and cookie
        /// </summary>
        /// <param name="url">The url that identifies the Internet resources </param>
        /// <param name="proxy">The proxy used to send the request. Pass null indicates that the request will be
        /// sent directly</param>
        /// <param name="cookie">The cookie data</param>
        /// <returns>Return null if the request cannot be created</returns>
        protected HttpWebRequest CreatePostRequest(string url, IWebProxy proxy, string cookie)
        {
            HttpWebRequest request = null;

            // Wait until all the changes of the parameters have applied
            if (!String.IsNullOrEmpty(url))
            {
                try
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.Method = "POST";
                    request.Proxy = proxy;
                    request.ContentLength = 0;
                    if (!String.IsNullOrEmpty(cookie)) request.Headers[HttpRequestHeader.Cookie] = cookie;
                }
                catch (UriFormatException) { }
            }

            return request;
        }

        /// <summary>
        /// Generate a unique id used to identify each network stream
        /// </summary>
        /// <returns>A unique string</returns>
        protected string GenerateUniqueID()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }

        /// <summary>
        /// Convert the source string to a equivalent base64 string
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        protected string GetBase64String(string source)
        {
            return Convert.ToBase64String(Encoding.ASCII.GetBytes(source));
        }

        /// <summary>
        /// Checks the status code to see if the script exists and runs properly
        /// </summary>
        /// <param name="code"></param>
        /// <returns>True if the code indicates that the connection is established successfully</returns>
        protected bool CheckStatusCode(HttpStatusCode code)
        {
            if (code == HttpStatusCode.InternalServerError ||
                code == HttpStatusCode.NotFound ||
                code == HttpStatusCode.Forbidden)
            {
                return false;
            }
            return true;
        }

        #endregion
    }
}
